import { DownOutlined } from '@ant-design/icons';
import { useMount } from 'ahooks';
import { Button, Tooltip } from 'antd';
import React, { useState } from 'react';

import { SvgIcon } from '@/components/icon';
import { t } from '@/locales/i18n';
import DialogModelSelect from '@/pages/app-orchestration/components/DialogModelSelect';
import { useSystemStore } from '@/store/useSystemStore';
import { LLMModelTypeEnum, llmModelTypeFilterMap } from '@/types/ai/constants';
import { SettingAIDataType } from '@/types/app/type';

type Props = {
  llmModelType?: `${LLMModelTypeEnum}`;
  defaultData: SettingAIDataType;
  onChange: (e: SettingAIDataType) => void;
  bg?: string;
};

const SettingLLMModel: React.FC<Props> = ({
  llmModelType = LLMModelTypeEnum.all,
  defaultData,
  onChange,
  bg = 'white',
}) => {
  const { llmModelList } = useSystemStore();
  const [isOpenAIChatSetting, setIsOpenAIChatSetting] = useState(false);

  const { model } = defaultData;

  const modelList = llmModelList.filter((model) => {
    if (!llmModelType) return true;
    const filterField = llmModelTypeFilterMap[llmModelType];
    if (!filterField) return true;
    // @ts-ignore
    return !!model[filterField];
  });

  const currentModel = modelList.find((item) => item.model === model);

  const selectedModel = currentModel || modelList[0];

  const onOpenAIChatSetting = () => setIsOpenAIChatSetting(true);
  const onCloseAIChatSetting = () => setIsOpenAIChatSetting(false);

  // Set default model
  useMount(() => {
    if (!model && modelList.length > 0) {
      onChange({
        ...defaultData,
        model: modelList[0].model,
      });
    }
  });

  return (
    <div className="relative">
      <Tooltip title={t('core.app.Setting ai property')}>
        <Button
          style={{
            width: '100%',
            justifyContent: 'flex-start',
            background: bg,
            textAlign: 'left',
            paddingLeft: 16,
          }}
          onClick={onOpenAIChatSetting}
        >
          <div className="flex w-full items-center justify-between">
            <div className="flex items-center">
              <SvgIcon size="24" icon={selectedModel?.avatar!} style={{ marginRight: 8 }} />
              <div>
                {model} <span className="text ml-2">{currentModel ? '' : '不可用'}</span>
              </div>
            </div>
            <DownOutlined />
          </div>
        </Button>
      </Tooltip>

      <DialogModelSelect
        open={isOpenAIChatSetting}
        defaultValue={defaultData}
        onCancel={onCloseAIChatSetting}
        onSubmit={(e) => {
          onChange(e);
          onCloseAIChatSetting();
        }}
      />
    </div>
  );
};

export default React.memo(SettingLLMModel);
